import akshare as ak
import logging
import pandas as pd
from typing import List, Dict
from utils.option_code import convert_option_symbol
from akshare_adapters import FinancialDataException
from core import BaseDataAdapter

logger = logging.getLogger(__name__)

class AKShareOptionAdapter(BaseDataAdapter):
    """期权数据适配器"""
    
    def __init__(self,**kwargs)-> None:
        super(AKShareOptionAdapter).__init__(**kwargs)
    
    @staticmethod
    def format_symbol(symbol: str) -> str:
        """标准化标的代码格式
        Args:
            symbol: 原始标的代码 (e.g. 600519.SH)
        Returns:
            标准化后的代码 (e.g. 600519)
        """
        return convert_option_symbol(symbol)
    
    @classmethod
    async def get_historical_data(cls, symbol: str, start: str, end: str) -> list:
        """获取期权历史数据"""
        try:
            akshare_symbol = cls.format_symbol(symbol)
            df = ak.option_finance_board(symbol=akshare_symbol)
            return cls.validate_data(df)
        except Exception as e:
            logger.error(f"期权数据获取失败 {symbol}: {str(e)}")
            raise FinancialDataException(f"期权数据异常: {str(e)}")
        
    @classmethod
    def validate_data(cls, df: pd.DataFrame) -> List[Dict]:
        return [{
                'timestamp': row['日期'].strftime("%Y-%m-%d"),
                'contract_id': row['合约代码'],
                'call_put': 'CALL' if '购' in row['名称'] else 'PUT',
                'strike_price': float(row['行权价']),
                'settlement': float(row['结算价']),
                'close': float(row['收盘价']),
                'volume': int(row['成交量']),
                'open_interest': int(row['持仓量']),
                'iv': float(row['隐含波动率'])
            } for _, row in df.iterrows()]